<?php
/**
 * 晒单活动
 */
namespace minisite\controllers;

use Yii;
use minisite\models\MActivityShowSearch;
use services\models\minisite\MActivityShowFeelReply;
use services\models\minisite\MActivityShow;
use services\models\minisite\MActivityShowFeel;

use services\models\minisite\MActivityShowFeelLikeClick;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use wap\controllers\CustomController;

/**
 * MActivityShowFeelLikeClickController implements the CRUD Macti for MActivityShowFeelLikeClick model.
 */
class MActivityShowController extends CustomController //\yii\web\Controller
{
    public  $enableCsrfValidation = false;
    public  $layout               = false;
    public  $frequently           = 'frequently:act_show_';
    public  $layout_data          = 'mini_the_sun';
    private $reply_expire         = 300;

    public function beforeAction($action)
    {
        $result = parent::beforeAction($action);
        $this->frequently .= $this->liketry_uid;
        return $result;
    }

    //验证提交数据规则
    public function behaviors()
    {
        return [
            'verbs' => [
                'class'   => VerbFilter::className(),
                'actions' => [

                ],
            ],
        ];
    }

    /**
     * 晒单活动首页
     */
    public function actionIndex()
    {
        //获取活动
        $mactive = MActivityShow::getActivityInfos();
        //获取活动类别
        $mactiveCategory = MActivityShowFeel::$CATEGORY;


        return $this->renderPartial('index', [
            'mactive'         => $mactive,
            'mactiveCategory' => $mactiveCategory,
            'uid'             => $this->liketry_uid,
            'loginUrl'        => $this->login_url,
        ]);

    }


    /**
     * 活动详情页
     * @param number $asf_id
     * @throws NotFoundHttpException
     */
    public function actionDetail($asf_id = 0)
    {
        if ($asf_id == 0 || empty($asf_id)) {
            throw new NotFoundHttpException('没有找到要访问的页面');
        }

        $asf = MActivityShowFeel::findOne(['id' => $asf_id]);

        if ($asf == null) {
            throw new NotFoundHttpException('没有找到要访问的页面');
        }
        $asf->addShowTimes();
        return $this->renderPartial('detail', [
            'asf' => $asf,
        ]);

    }

    /**
     * 参与活动
     */
    public function actionJoinActivity()
    {
        if (Yii::$app->request->isPost) {
            $c_content = Yii::$app->request->post("content", ''); //获取输入内容
            /** @var int $act_id */
            $act_id  = (int)Yii::$app->request->post("act_id", 0);  //获取活动id
            $c_image = Yii::$app->request->post("c_image", ''); //获取图片ids
            //设置返回json格式
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


            if (!$this->liketry_uid) {
                return ['flag' => false, 'msg' => '请登录后再参与活动'];
            }

            $res = MActivityShow::findOne(['id' => $act_id]);

            if ($res === null) {
                return ['flag' => false, 'msg' => '未查询到活动'];
            }
            if ($res->c_status == 0) {
                return ['flag' => false, 'msg' => '当前活动已经关闭'];
            }
            if (empty($c_content)) {
                return ['flag' => false, 'msg' => '请输入你想说的话~'];
            }

            if (mb_strlen($c_content, 'UTF8') > 500) {
                return ['flag' => false, 'msg' => '回复内容字数限制500字'];
            }

            if (empty($c_image)) {
                return ['flag' => false, 'msg' => '请上传图片！'];
            }
            if (!preg_match('/^[\d,]+$/', $c_image)) {
                return ['flag' => false, 'msg' => '请上传图片！'];
            }

            $c_image = preg_replace('/,+/', ',', $c_image);

            $image_arr = explode(',', $c_image);
            if (count($image_arr) > 3) {
                return ['flag' => false, 'msg' => '图片只能上传三张'];
            }

            //根据活动id获取活动名称
            $detail_info = MActivityShowSearch::getActivityDetailById($act_id);

            $model = new MActivityShowFeel();

            $model->as_id     = $act_id;
            $model->c_content = $c_content;
            $model->c_image   = $c_image;
            $model->c_channel = 1;
            $model->c_name    = $detail_info->c_name;
            $model->uid       = $this->liketry_uid;

            if ($model->save(true)) {
                return ['msg' => '添加成功', 'flag' => true];
            } else {
                return ['msg' => $model->getErrors(), 'flag' => false];
            }

        } else {
            
            if (!$this->liketry_uid) {
                return $this->redirect($this->login_url);
            }
            
            $act_id = (int)Yii::$app->request->get("act_id", 0);
            //获取活动详情中的name
            $detail_info = MActivityShowSearch::getActivityDetailById($act_id);

            return $this->render('join', [
                'detail_info' => $detail_info,
            ]);
        }

    }


    /**
     * 参与心得
     * @return string[]|boolean[]|string
     */
    public function actionJoinShare()
    {
        if (Yii::$app->request->isPost) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $c_content = Yii::$app->request->post("content", '');//参与内容
            $c_name    = Yii::$app->request->post("c_name", ''); //品牌名称
            $c_image   = Yii::$app->request->post("c_image", ''); //图片ids

            if (!$this->liketry_uid) {
                return ['flag' => false, 'msg' => '请登录后再参与心得'];
            }
            if (empty($c_name)) {
                return ['flag' => false, 'msg' => '一定要输入品牌和产品名称'];
            }
            if (mb_strlen($c_name, 'UTF8') > 20) {
                return ['flag' => false, 'msg' => '品牌和产品名称限制20字'];
            }
            if (empty($c_content)) {
                return ['flag' => false, 'msg' => '请输入心得内容'];
            }
            if (mb_strlen($c_name, 'UTF8') > 500) {
                return ['flag' => false, 'msg' => '回复内容字数限制500字'];
            }
            if (empty($c_image)) {
                return ['flag' => false, 'msg' => '请上传图片！'];
            }
            if (!preg_match('/^[\d,]+$/', $c_image)) {
                return ['flag' => false, 'msg' => '请上传图片！'];
            }

            $c_image = preg_replace('/,+/', ',', $c_image);

            $image_arr = explode(',', $c_image);
            if (count($image_arr) > 3) {
                return ['flag' => false, 'msg' => '图片只能上传三张'];
            }

            $model            = new MActivityShowFeel();
            $model->c_content = $c_content;
            $model->c_image   = $c_image;
            $model->c_channel = 2;
            $model->c_name    = $c_name;
            $model->uid       = $this->liketry_uid;

            if ($model->save(true)) {
                return ['flag' => true, 'msg' => '添加成功'];
            } else {
                return ['flag' => false, 'msg' => $model->getErrors()];
            }

        } else {
            
            if (!$this->liketry_uid) {
                return $this->redirect($this->login_url);
            }
            
            return $this->render('share');
        }

    }

    /**
     * 查询活动详情
     */
    public function actionShareList()
    {
        $id = Yii::$app->request->get("activity_id", 1);
        //获取活动详情
        $detail_info = MActivityShowSearch::getActivityDetailById($id);
        return $this->render('share-list', [
            'detail_info' => $detail_info,
            'uid'         => $this->liketry_uid,
            'loginUrl'    => $this->login_url,
        ]);
    }

    /**
     * 获取当前活动下面的参与内容
     */
    public function actionGetList()
    {

        $msg                        = ['html' => '', 'lastPage' => false, 'flag' => true];
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $as_id                      = Yii::$app->request->get("act_id", 0);

        $page      = Yii::$app->request->get("page", 0);//获取当前页
        $page_size = 10;//设置分页记录

        if (empty($as_id)) {
            return ['flag' => false, 'msg' => '参数不正确'];
        }

        //获取当前页记录
        $result = MActivityShowSearch::getActivitShowFeelInfos($as_id, $page, $page_size, (int)$this->liketry_uid);

        //获取当前总记录
        $count = $result['total'];

        if ((($page + 1) * $page_size) > $count) {
            $msg['lastPage'] = true;
        }
        $msg['html'] = $this->renderPartial('share-list-ajax', ['info' => $result['records']]);

        return $msg;
    }

    /**
     * Finds the MActivityShowFeelLikeClick model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return MActivityShowFeelLikeClick the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = MActivityShowFeelLikeClick::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 点赞
     * 参数 asf_id
     * @param $asf_id
     * @return array [boolean, asf_id]
     */
    public function actionClickLike($asf_id = 0)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        if (!$this->openid) {
            return ['flag' => false, 'msg' => '微信授权后才可以点赞'];
        }
        if (empty($asf_id)) {
            return new NotFoundHttpException('404');
        }

        $result = MActivityShowFeelLikeClick::clickLike($asf_id, $this->openid);

        if ($result) {
            return ['flag' => $result, 'asf_id' => $asf_id];
        }

        return ['flag' => $result, 'asf_id' => $asf_id, 'msg' => '每个人只能点一次噢！'];

    }

    /**
     * 用户提交评论
     * @return array
     *
     */
    public function actionReply()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        if (!$this->liketry_uid) {
            return ['flag' => false, 'msg' => '请登录后再评论'];
        }
        $content = Yii::$app->request->get('c_content', '');
        if (empty($content)) {
            return ['flag' => false, 'msg' => '评论内容不能为空'];
        }
        if (mb_strlen($content, 'UTF8') > 50) {
            return ['flag' => false, 'msg' => '评论内容不得大于50字'];
        }

        /**
         *  3秒内多次提交验证
         * 点击发送按钮，用户3秒内重复提交超过3次，提示：你操作的太快了，小试要晕了~过5分钟后才可再次发送评论。
         */
        $frequently       = Yii::$app->redis->hgetall($this->frequently);
        $str_five_minutes = '你操作的太快了，小试要晕了~过5分钟后才可再次发送评论';

        if (!empty($frequently)) {
            if ($frequently['lock'] != 0) {
                if (time() - $frequently['datetime'] < $this->reply_expire) {
                    return ['flag' => false, 'msg' => $str_five_minutes];
                } else {
                    Yii::$app->redis->hmset($this->frequently, ['lock' => '0', 'datetime' => time(), 'times' => 1]);
                }

            } else {
                if (time() - $frequently['datetime'] <= 3) {
                    if ($frequently['times'] >= 2) {
                        Yii::$app->redis->hmset($this->frequently, ['lock' => '1', 'datetime' => time(), 'times' => 0]);
                        return ['flag' => false, 'msg' => $str_five_minutes];
                    } else {
                        Yii::$app->redis->hmset($this->frequently, ['lock' => '0', 'datetime' => time(), 'times' => $frequently['times'] + 1]);
                    }
                } else {
                    Yii::$app->redis->hmset($this->frequently, ['lock' => '0', 'datetime' => time(), 'times' => 1]);
                }
            }
        } else {
            Yii::$app->redis->hmset($this->frequently, ['lock' => '0', 'datetime' => time(), 'times' => 1]);
        }

        $new            = new MActivityShowFeelReply();
        $new->as_id     = Yii::$app->request->get('as_id', 0);
        $new->asf_id    = Yii::$app->request->get('asf_id', 0);
        $new->c_content = $content;
        $new->db_time   = date('Y-m-d H:i:s');
        $new->uid       = $this->liketry_uid;
        $arr[]          = $new;
        if ($new->save(true)) {
            $html = $this->renderAjax('detail-list-ajax', ['data' => (Object)$arr]);
            return ['flag' => true, 'msg' => '', 'data' => $html];
        }
        return ['flag' => false, 'msg' => $new->getErrors()];

    }

    /**
     * 用户回复列表
     * @return array
     */
    public function actionReplyList()
    {
        $pageSize = 10;

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $asf_id                     = Yii::$app->request->get('asf_id', '');
        $page                       = (int)Yii::$app->request->get('page', 0);
        if (empty($asf_id)) {
            return ['flag' => false, 'msg' => '参数不正确'];
        }

        $query = MActivityShowFeelReply::find()->where(['asf_id' => $asf_id]);
        $data  = $query->limit($pageSize)->offset($pageSize * $page)->all();
        $html  = $this->renderPartial('detail-list-ajax', [
            'data' => $data,
        ]);
        return ['html' => $html, 'lastPage' => count($data) < $pageSize ? true : false];
    }

    /**
     * 首页ajax请求数据
     * @return boolean[]|string[]
     */
    public function actionIndexListAjax()
    {

        $pageSize = 10;
        $page     = (int)Yii::$app->request->get('page', 0);
        $category = (int)Yii::$app->request->get('category', 0);

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        /** @var MActivityShowFeel $asfModel */
        $asfModel = MActivityShowFeel::find()->innerJoinWith('mActivityShowFeelStatistics')
                                     ->orderBy(['c_date' => SORT_DESC, 'c_score' => SORT_DESC])
                                     ->andFilterWhere(['c_channel' => 2, 'c_status' => 1]);


        if ($this->liketry_uid) {
            $asfModel = $asfModel->orFilterWhere(['uid' => $this->liketry_uid, 'c_status' => 0, 'c_channel' => 2]);
        }

        if ($category > 0 && array_key_exists($category, MActivityShowFeel::$CATEGORY) !== false) {
            /** @var MActivityShowFeel $asfModel */
            $asfModel = $asfModel->andFilterWhere(['c_category' => $category]);
        }

        $data = $asfModel->offset($pageSize * $page)->limit($pageSize)->all();


        $html = $this->renderPartial('index-list-ajax', [
            'data' => $data,
        ]);

        return ['html' => $html, 'lastPage' => count($data) < $pageSize ? true : false];

    }


}
